#!/usr/bin/perl

use lib::abs qw( base_lib lib );
use JIP::ToolSet; # load my commonly-used modules in a single import

use File::Find::Rule;                    # CPAN modules
use DateTime;                            #
use English qw( -no_match_vars );        #
use Carp qw( croak );                    #
use File::Spec::Functions qw( catfile ); #
use FindBin qw( $RealBin );              #

use Configurator; # searcher custom modules
use Log::Console; #
use Proc::Lock;   #

#-- init settings -------------------------------------------------------------
my $conf = Configurator->new( conf => 'robo_conf.pm' )->getSettings;

#-- init log -------------------------------------------------------------------
our $log = Log::Console->new( log_level => 'all' );

#-- signal handlers ------------------------------------------------------------
require( catfile( $RealBin, 'signal_handlers.pl' ) );

#-- setup lock -----------------------------------------------------------------
$log->Note('setup lock');

my $process = Proc::Lock->new( lock_file => $conf->make_clean->lock_file );

$process->lock;

#-- main processing ------------------------------------------------------------
$log->Note('-- main ---------------------------------------------------------');

# директории в которых проводится очистка
my @directories = (
    $conf->fast_scanner->log_dir,
    $conf->slow_scanner->log_dir,
    $conf->crawler->log_dir,
    $conf->filter->log_dir,
    $conf->build->log_dir,
);

my $ageing = DateTime->now
                     ->subtract( days => $conf->make_clean->ageing )
                     ->epoch;

foreach my $eachDirLocation ( @directories ) {
    unless ( -d $eachDirLocation ) {
        $log->Error( 'destination '. $eachDirLocation .' must be a directory' );

        next;
    }

    $log->Note( 'current directory: '. $eachDirLocation );

    my @unusedFiles = File::Find::Rule->file()
                                      ->name( '*.log' )
                                      ->ctime( '<'. $ageing )
                                      ->in( $eachDirLocation );

    foreach my $eachFileLocation ( @unusedFiles ) {
        $log->Note( 'unlink '. $eachFileLocation );

        unlink $eachFileLocation
            or croak 'cannot unlink '. $eachFileLocation .': '. $OS_ERROR;
    }
}

#-- finalyze -------------------------------------------------------------------
$log->Note('-- finalyze -----------------------------------------------------');

$log->Note('unset lock...') and $process->unlock;

$log->Note('exiting');

#-- end ------------------------------------------------------------------------
